package com.hcinfos.gsoo.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.Groupbuy;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;
import com.baidu.location.LocationClient;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.MainFocusAdapter;
import com.hcinfos.gsoo.adapter.RecommendAdapter;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.db.DBUtil;
import com.hcinfos.gsoo.enity.City;
import com.hcinfos.gsoo.enity.GroupByInfo;
import com.hcinfos.gsoo.enity.Version;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.interaze.DialogCallBack;
import com.hcinfos.gsoo.json.VersionJson;
import com.hcinfos.gsoo.service.LocationService;
import com.hcinfos.gsoo.util.ApkDownloadUtil;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.NetWorkHelper;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.VersionUtil;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

/**
 * tab
 * 
 * @author john
 * 
 */

public class HomeActivity extends Activity implements OnPageChangeListener,
		OnClickListener, OnPoiSearchListener {

	private ViewPager viewPager;
	private LinearLayout viewGroup;
	private ImageView imageView;
	private ImageView[] imageViews;
	private ListView listView;

	private TextView address_tv;
	private ImageView close_iv;
	private RelativeLayout address_rl;

	private LocationManagerProxy aMapLocManager = null;
	private AMapLocation aMapLocation;// 用于判断定位超时

	private SharePreferenceUtil util;
	private LinearLayout loading_layout;
	private RecommendAdapter recommendAdapter;

	private ProgressBar requestLoadingProgress;
	private TextView RequestLoadingText;
	private RelativeLayout search_rl;
	private EditText search_edit;
	private ImageView click_iv;
	private boolean isSameCity = true;
	private DBUtil dbUtil;

	public static boolean isChangeData = false;
	private MainFocusAdapter viewPagerAdapter;
	private LocationClient locationClient;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.frame_content);

		locationClient = ((GsooApplication) getApplication()).mLocationClient;
		IntentFilter filter = new IntentFilter(LocationService.LOCATION_ACTION);
		registerReceiver(locationReceiver, filter);
		groupsList = new ArrayList<GroupByInfo>();
		initRes();
		util = new SharePreferenceUtil(this, "setting");
		dbUtil = DBUtil.newInstance(this);
	}

	@Override
	protected void onResume() {
		obtainData();
		super.onResume();

	}

	private void obtainData() {
		isSameCity = GsooApplication.isSameCity;
		City city = (City) util.loadObject("city");
		listView.setVisibility(View.GONE);
		loading_layout.setVisibility(View.VISIBLE);
		requestLoadingProgress.setVisibility(View.VISIBLE);
		groupsList.clear();
		try {
			if (city != null) {
				if (GsooApplication.lat == null) {
					// 启动定位服务
					// Intent locationService = new Intent(this,
					// LocationService.class);
					// startService(locationService);
					locationClient.start();
				} else {
					if (GsooApplication.cityName != null
							&& GsooApplication.cityName.equals(city.getName())) {
						isSameCity = true;
					} else {
						isSameCity = false;
					}
					cityName = city.getName();
					doSearchQuery();
				}

			} else {
				// 城市未开通
			}
		} catch (Exception e) {

			LogUtil.e("wxf", "obtainData =" + e.toString());
		}

		if (isSameCity) {
			if (GsooApplication.address != null) {
				address_tv.setText(GsooApplication.address);
			} else {
				address_tv.setText("定位失败");
			}
		} else {
			address_tv.setText("你正在查看的是 " + city.getName() + " 数据");
			//
		}

	}

	BroadcastReceiver locationReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			LogUtil.d("wxf", "HomeActivity  location Receiver........");
			obtainData();
		}

	};

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
	}

	private void initRes() {

		loading_layout = (LinearLayout) findViewById(R.id.loading_layout);
		requestLoadingProgress = (ProgressBar) findViewById(R.id.requestLoadingProgress);
		RequestLoadingText = (TextView) findViewById(R.id.RequestLoadingText);

		address_tv = (TextView) findViewById(R.id.address_tv);
		close_iv = (ImageView) findViewById(R.id.close_iv);
		close_iv.setOnClickListener(this);
		address_rl = (RelativeLayout) findViewById(R.id.address_rl);

		listView = (ListView) findViewById(R.id.listView);
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		viewGroup = (LinearLayout) findViewById(R.id.viewGroup);
		List<String> list = new ArrayList<String>();
		list.add("tes1");
		list.add("tes2");
		recommendAdapter = new RecommendAdapter(this, groupsList);
		listView.setAdapter(recommendAdapter);
		imageViews = new ImageView[list.size()];
		for (int i = 0; i < list.size(); i++) {
			LinearLayout.LayoutParams parmas = new LinearLayout.LayoutParams(
					12, 12);
			parmas.leftMargin = 5;
			parmas.rightMargin = 5;
			imageView = new ImageView(this);
			imageView.setLayoutParams(parmas);
			imageViews[i] = imageView;
			if (i == 0) {
				imageView.setBackgroundResource(R.drawable.new_focus_icon);
			} else {
				imageView.setBackgroundResource(R.drawable.new_unfocus_icon);
			}
			viewGroup.addView(imageView);
		}

		viewPagerAdapter = new MainFocusAdapter(list, this);
		MainFocusAdapter.test = 0;
		viewPager.setAdapter(viewPagerAdapter);
		viewPager.setOnPageChangeListener(this);
		viewPager.setCurrentItem(0);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				Intent intent = new Intent(HomeActivity.this,
						WebViewActivity.class);
				intent.putExtra("url", groupsList.get(position).getUrl());
				startActivity(intent);
			}
		});

		search_rl = (RelativeLayout) findViewById(R.id.search_rl);
		search_rl.setOnClickListener(this);
		click_iv = (ImageView) findViewById(R.id.click_iv);
		click_iv.setOnClickListener(this);
		if (GsooApplication.address != null) {
			address_tv.setText(GsooApplication.address);
		}

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	private Intent intent;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.click_iv:
			intent = new Intent(this, SearchActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
			break;

		case R.id.close_iv:
			address_rl.setVisibility(View.GONE);
			break;

		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (locationReceiver != null)
			unregisterReceiver(locationReceiver);
	}

	private PoiSearch.Query query;
	private int currentPage = 0;
	private PoiSearch poiSearch;
	private List<PoiItem> poiItems;
	private String cityName = null;
	private final int OBTAIN_GROUPBY_START = 0x1120;
	private final int OBTAIN_GROUPBY_SUCCESS = OBTAIN_GROUPBY_START + 1;
	private final int OBTAIN_GROUPBY_FAIL = OBTAIN_GROUPBY_START + 2;
	private final int OBTAIN_GROUPBY_EMPTY = OBTAIN_GROUPBY_START + 3;
	private final int OBTAIN_LOCATION_CITY = OBTAIN_GROUPBY_START + 4;

	protected void doSearchQuery() {

		query = new PoiSearch.Query("", "餐饮", cityName);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(10);// 设置每页最多返回多少条poiitem
		query.setPageNum(currentPage);// 设置查第一页
		query.setLimitDiscount(false);
		query.setLimitGroupbuy(true);
		poiSearch = new PoiSearch(this, query);
		poiSearch.setOnPoiSearchListener(this);
		if (isSameCity) {
			LatLonPoint lp = new LatLonPoint(GsooApplication.lat,
					GsooApplication.lng);
			poiSearch.setBound(new SearchBound(lp, 2000, true));
		}
		poiSearch.searchPOIAsyn();// 异步搜索
	}

	public void doSearchPoiDetail(String poiId) {
		if (poiSearch != null && poiId != null) {
			poiSearch.searchPOIDetailAsyn(poiId);
		}
	}

	@Override
	public void onPoiItemDetailSearched(PoiItemDetail detail, int rCode) {
		if (rCode == 0) {
			if (detail != null) {
				GroupByInfo groupBy = new GroupByInfo();
				List<Groupbuy> list = detail.getGroupbuys();
				if (list != null && list.size() > 0) {
					groupBy.setDistance(distanceMap.get(detail.getPoiId()));
					groupBy.setShopName(detail.toString());
					groupBy.setDataType(GroupByInfo.TYPES[1]);
					groupBy.setUrl(list.get(0).getUrl());
					groupBy.setList(list);
					groupsList.add(groupBy);
				} else {
					handler.sendEmptyMessage(OBTAIN_GROUPBY_EMPTY);
				}

			}
		}
		Message msg = handler.obtainMessage();
		msg.what = OBTAIN_GROUPBY_SUCCESS;
		handler.sendMessage(msg);
	}

	private Map<String, Integer> distanceMap = new HashMap<String, Integer>();

	@Override
	public void onPoiSearched(PoiResult result, int rCode) {
		if (rCode == 0) {
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiItems = result.getPois();
					if (poiItems != null && poiItems.size() > 0) {
						for (PoiItem item : poiItems) {
							distanceMap
									.put(item.getPoiId(), item.getDistance());
							doSearchPoiDetail(item.getPoiId());
						}
					}
				}
			}

		} else {
			Message msg = handler.obtainMessage();
			msg.what = OBTAIN_GROUPBY_FAIL;
			handler.sendMessage(msg);
		}

	}

	private List<GroupByInfo> groupsList;

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case OBTAIN_LOCATION_CITY:
				//
				// GsooApplication.currentCity = dbUtil
				// .queryCityByCityName(cityName);
				break;
			case OBTAIN_GROUPBY_START:
				if (GsooApplication.cacheGroupList != null
						&& GsooApplication.cacheGroupList.size() > 0) {
					groupsList = GsooApplication.cacheGroupList;
					handler.sendEmptyMessage(OBTAIN_GROUPBY_SUCCESS);
				} else {
					doSearchQuery();
				}

				break;
			case OBTAIN_GROUPBY_SUCCESS:
				if (groupsList != null && groupsList.size() > 0) {
					GsooApplication.cacheGroupList = groupsList;
				}
				loading_layout.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				Collections.sort(groupsList);
				recommendAdapter.setDataChange(groupsList);
				break;
			case OBTAIN_GROUPBY_FAIL:
				requestLoadingProgress.setVisibility(View.GONE);
				RequestLoadingText.setText("加载失败");
				break;
			case OBTAIN_GROUPBY_EMPTY:

				requestLoadingProgress.setVisibility(View.GONE);
				RequestLoadingText.setText("抱歉!暂无团购数据");
				break;

			}
		};
	};

	@Override
	public void onPageSelected(int position) {
		setImageBackground(position);
		switch (position) {
		case 0:
			GsooApplication.sildingMenu
					.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
			break;
		default:
			GsooApplication.sildingMenu
					.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
			break;
		}
	}

	private void setImageBackground(int selectItems) {
		for (int i = 0; i < imageViews.length; i++) {
			if (i == selectItems) {
				imageViews[i].setBackgroundResource(R.drawable.new_focus_icon);
			} else {
				imageViews[i]
						.setBackgroundResource(R.drawable.new_unfocus_icon);
			}
		}
	}

	long waitTime = 2000;
	long touchTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& KeyEvent.KEYCODE_BACK == keyCode) {
			long currentTime = System.currentTimeMillis();
			if ((currentTime - touchTime) >= waitTime) {
				Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
				touchTime = currentTime;
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
